package com.chenfan.ccp.util.tool;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.chenfan.ccp.plug.mybatis.util.MybatisPlus;
import com.chenfan.ccp.plug.mybatis.util.MybatisPlusBuild;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取Id的工具类
 */
public class IdUtil {

    private static final ThreadLocal<Long> idCache = new TransmittableThreadLocal<>();
    private static final ThreadLocal<Long> totalCache = new TransmittableThreadLocal<>();
    private static final Logger logger = LoggerFactory.getLogger(IdUtil.class);


    private IdUtil() {

    }

    public static Long getId() {

        Long id = idCache.get();
        if (id == null) {
            logger.warn("当前线程={} 获取不到Id,请检查是否设置", Thread.currentThread().getName());
        } else {
            idCache.remove();
        }

        return id;
    }

    public static void setId(Long id) {
        if (id == null || id <= 0) {
            logger.warn("所传Id不符合规范 Id={}", id);
            return;
        }
        idCache.set(id);

    }

    public static long getTotal() {
        Long total = totalCache.get();
        if (total != null) {
            totalCache.remove();
        } else {
            total = 0L;
        }
        return total;
    }

    private static void setTotal(long total) {
        totalCache.set(total);

    }

    public static long setTotal(MybatisPlusBuild build) {
        long count = MybatisPlus.getInstance().count(build.cached());
        setTotal(count);
        return count;
    }


}


